package com.nf.health.app.activity.home.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.easeui.EaseConstant;
import com.nf.health.app.Constants;
import com.nf.health.app.R;
import com.nf.health.app.mydoctor.adapter.GroupNewAdapter;
import com.nf.health.app.customview.DragListView;
import com.nf.health.app.customview.EmptyView;
import com.nf.health.app.fragment.IBaseFragment;
import com.nf.health.app.utils.ViewUtil;

import java.util.ArrayList;
import java.util.List;


/**
 *
 * 类功能描述：* 获取用户所添加的群组</br>
 * @author 于亚豪
 * @version 1.0 </p> 修改时间：</br> 修改备注：</br>
 */
public class AttentionGroupFragment extends IBaseFragment {
    //创建群

    private ImageView iv_search_paint1;
    private EditText et_paint_group_search1;
    public static final String TAG = "GroupsActivity";

    protected List<EMGroup> grouplist;
    private GroupNewAdapter groupAdapter;
    private InputMethodManager inputMethodManager;
    public static AttentionGroupFragment instance;
    //@Bind(R.id.consul_listview)
    DragListView consulListview;
    /************当前的页数************/
    private int page;
    /********ListView的高度*********/
    /***********用于刷新广播的actyion*********/
    public static final String IS_TO_FORBIT_USER_TO_REFRESH= "is_to_forbit_user_to_refresh";
    private BroadcastReceiver receiver;
    //private String is_frash = null; //刷新广播玻璃的标识
    private EmptyView emptyView;
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        addViewFillInRoot(R.layout.fragment_attation);
       // ButterKnife.bind(getActivity(),rootView);
        consulListview = ViewUtil.getView(getActivity(), R.id.consul_att_listview);
        initViews();
    }
    Handler handler = new Handler(){
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    refresh() ;
                    break;
                case 1:
                    grouplist = (List<EMGroup>) msg.obj;
                    if(grouplist == null || grouplist.size() == 0){
                        consulListview.setEmptyView(emptyView);
                    }else {
                        if(groupAdapter == null){
                            groupAdapter = new GroupNewAdapter(getActivity(), grouplist);
                            consulListview.setAdapter(groupAdapter);
                        }else{
                            groupAdapter.setMyDataChanged(grouplist);
                        }
                    }
                    break;
                default:
                    break;
            }
        };
    };
    private void initViews(){
        registReceiver();
        instance = this;
        inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        consulListview.setRefreshableAndLoadMoreable(true, true);
        grouplist = new ArrayList<EMGroup>();
        groupAdapter = new GroupNewAdapter(getActivity(),grouplist);
        consulListview.setAdapter(groupAdapter);
        emptyView = new EmptyView(getActivity());//要显示的空布局
        emptyView.mustCallInitWay(consulListview).setImageViewParams(120,120).setMyRefreshShow(View.VISIBLE).
        setOnRefreshData(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLoading("加载中...");
                handler.sendEmptyMessageDelayed(0,1000);
            }
        });
        loadData();
        consulListview.setRefreshableAndLoadMoreable(true, false);
        consulListview.setOnRefreshAndLoadMoreListener(new DragListView.onRefreshAndLoadMoreListener() {

            @Override
            public void onRefresh() {
             handler.sendEmptyMessageDelayed(0,1500);
            }

            @Override
            public void onLoadMore() {
            }
        });
        consulListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle = new Bundle();
                int newMyPosion = position - 1;
                bundle.putString(EaseConstant.EXTRA_USER_ID, grouplist.get(newMyPosion).getGroupId());
//                ActivityUtils.showActivity(getActivity(), ChatGroupActivity.class, bundle);
            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        instance = null;
    }

    /********刷新数据*******/
    public void refresh() {
        grouplist = EMClient.getInstance().groupManager().getAllGroups();

        if(grouplist == null || grouplist.size() == 0){
            consulListview.setEmptyView(emptyView);
        }else{
            if(groupAdapter == null){
                groupAdapter = new GroupNewAdapter(getActivity(), grouplist);
                consulListview.setAdapter(groupAdapter);
            }else{
                groupAdapter.setMyDataChanged(grouplist);
            }
        }
        consulListview.completeRefresh();
        hideLoading();
    }
    /**********加载数据***刷新数据**/
    private void loadData(){
        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        grouplist = EMClient.getInstance().groupManager().getAllGroups();
                        Message msg = handler.obtainMessage();
                        msg.what = 1;
                        msg.obj = grouplist;
                        handler.sendMessage(msg);
                    }
                }
        ).start();
    }
    //注册 广播和接收
    private void registReceiver() {
        receiver = new BroadcastReceiver(){

            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if(Constants.EXIST_SPECIAL_SIGN_FORBIT_GROUP_ID_REFRESH.equals(action)){
                       // if(is_frash.equals(Constant.EXIST_SPECIAL_SIGN_FORBIT_GROUP_ID_REFRESH)){//是群聊，进项禁言
                        //}
                refresh();

                }
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.EXIST_SPECIAL_SIGN_FORBIT_GROUP_ID_REFRESH);
        getActivity().registerReceiver(receiver, filter);

    }
}

